package com.tsl.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.tsl.reggie.common.BaseContext;
import com.tsl.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求里的URI并且将session里的用户id放入Thread
        String uri = request.getRequestURI();
        BaseContext.setUserId((Long)request.getSession().getAttribute("userId"));
        //2.设置放行的URI地址
        String [] uris=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //3.判断是否放行
        Boolean check = check(uris, uri);
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //4-1.判断是否登录
        Object userId = request.getSession().getAttribute("userId");

        if (userId!=null){
            filterChain.doFilter(request, response);
            return;

        }


        //5.未登录则返回未登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }
    public Boolean check(String[] uris,String uri){
        for (String u : uris) {
            boolean match = PATH_MATCHER.match(u, uri);
            if (match){
                return match;
            }
        }
        return false;
    }
}
